<template>
  <!-- 评论列表 -->
  <div>
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
    >
      <!-- 评论cell子组件 -->
      <CommentItem
        v-for="(item, index) in list"
        :key="index"
        :title="item.content"
        :comment="item"
        @click-reply="$emit('click-reply', $event)"
      />
    </van-list>
  </div>
</template>

<script>
import { getArticleComment } from '@/api/comment.js'
import CommentItem from '@/components/comment-item.vue'

export default {
  name: 'AricleComment',
  components: {
    CommentItem
  },
  props: {
    // 文章类型 a为文章评论  c为评论回复
    type: {
      type: String,
      default: 'a'
    },
    // 文章ID 或者评论ID
    source: {
      type: [Number, Object],
      required: true
    },
    // 评论列表数据
    list: {
      type: Array,
      required: true
    }
  },
  data () {
    return {
      loading: false,
      finished: false,
      offset: null, // 获取评论数据的偏移量，值为评论id，表示从此id的数据向后取，不传表示从第一页开始读取数据
      limit: 10, // 获取的评论数据个数
      totalCount: 0, // 评论总数
      // list错误状态
      error: false
    }
  },
  methods: {
    async onLoad () {
      // 请求数据
      try {
        const { data: { data: res } } = await getArticleComment({
          type: this.type,
          source: this.source + '',
          offset: this.offset,
          limit: this.limit
        })
        console.log(res)
        // 保存数据
        this.totalCount = res.total_count
        this.list.push(...res.results)
        this.$emit('updatetotal', this.totalCount)
        // 加载状态结束
        this.loading = false
        // 全部数据加载完成
        if (this.list.length >= res.total_count) {
          this.finished = true
        } else {
          this.offset = res.last_id
        }
      } catch (err) {
        this.loading = false
        this.error = true
      }
    }
  }
}
</script>

<style scoped lang='less'>
</style>
